package com.isoftstone.studentregistration.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.isoftstone.studentregistration.pojo.Users;
import com.isoftstone.studentregistration.service.UserService;
import com.isoftstone.studentregistration.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class UserController {
    //注入UserService实例
    @Autowired
    private UserService userService;
    private LineCaptcha lineCaptcha;
    @PostMapping("/user")
    public Result<?> insertUser(@RequestBody Users user)
    {
        return userService.insertUser(user);
    }
    //修改用户信息
    @PutMapping("/user")
    public Result<?> updateUser(@RequestBody Users user)
        {
            return userService.updateUser(user);
        }
    //删除用户
    @DeleteMapping("/user/{id}")
    public Result<?> deleteUser(@PathVariable Integer id)
        {
            return userService.deleteUser(id);
        }
    //分页查询用户
    @GetMapping("/user")
    public Result<?> queryUserById(@RequestParam(defaultValue = "1") Integer currentPage, @RequestParam(defaultValue = "10") Integer pageSize )
            {
                Page page = userService.queryAllUsers(currentPage, pageSize);
                PageInfo<Object> pageInfo = new PageInfo<>(page);
                return Result.success(pageInfo);
            }
            //根据id查询用户
    @GetMapping("/user/{id}")
    public Result<?> queryUserById(@PathVariable Integer id)
                {
                    return Result.success(userService.queryUserById(id));
                }
     //验证码
    @GetMapping("/captcha")
    public void captcha(HttpServletResponse response)
    {
        lineCaptcha = CaptchaUtil.createLineCaptcha(125, 45);
        lineCaptcha.setBackground(new Color(101, 238, 218));
        try {
            ServletOutputStream os = response.getOutputStream();
            lineCaptcha.write(os);
            os.flush();
            os.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //用户登录
    @PostMapping("/login")
    public Result<?> login(@RequestBody Map<String, String> user)
    {
       //获取用户输入的验证码
        String code = user.get("code");
        System.out.println("验证码：" + code);
        //验证码验证
        if (!lineCaptcha.verify(code)) {
            return Result.error("验证码错误");
        }
        return userService.login(user.get("phone"), user.get("password"));
    }
    @GetMapping("/export")
    public void exportExcel(HttpServletResponse response) throws IOException
    {
        userService.exportExcel(response);
    }
    //导入Excel
    @PostMapping("/import")
    public Result<?> importExcel( MultipartFile file) throws IOException
    {
        InputStream is= file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader( is);
        List<Users> list = reader.readAll(Users.class);
        try{
               list.stream().forEach(user ->
                userService.insertUser(user));
        } catch (Exception e){
            e.printStackTrace();
            return Result.error("导入失败");
        }
        return Result.success("导入成功");
    }

    //批量删除
    @DeleteMapping("/user/batch")
    public Result<?> batchDeleteUser(@RequestBody List<Integer> ids) {
        try {
            int deletedCount = userService.batchDeleteUser(ids);
            return Result.success("成功删除 " + deletedCount + " 个用户");
        } catch (Exception e) {
            return Result.error("批量删除失败: " + e.getMessage());
        }
    }



}
